package com.hcl.orm.core.executor.nativesql.tablestruct;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.hcl.orm.core.annotation.DBType;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.InvalidParameterException;
import java.util.List;

import static com.hcl.orm.core.executor.DaoMethodExecutor.jdbcTemplateMapperFactory;

/**
 * @author hucl
 * @projectName hcl-orm
 * @description: TODO
 * @date 2021/8/1613:49
 */
@Component
public class MysqlTsExecutor implements TsSqlExecutor {
    private static final String COLUMS_SQL_TMPL = "select column_name,data_type from information_schema.`columns` " +
            " where table_name = '{}'";
    @Resource
    private JdbcOperations jdbcOperations;

    @Override
    public List<TableColumn> getTableColumns(String tableName) {
        String[] strSchemaAndTable = StrUtil.split(tableName, ".");
        String executeSql = null;
        if (strSchemaAndTable.length == 1) {
            executeSql = StrUtil.format(COLUMS_SQL_TMPL, strSchemaAndTable[0]);
        } else if (strSchemaAndTable.length == 2) {
            executeSql = StrUtil.format(COLUMS_SQL_TMPL, strSchemaAndTable[1],
                    StrUtil.format("and table_schema ='{}'", strSchemaAndTable[0]));
        }
        if (StrUtil.isEmpty(executeSql)) {
            throw new InvalidParameterException("invalid function params.");
        }
        ResultSetExtractor mapper = jdbcTemplateMapperFactory.newResultSetExtractor(TableColumn.class);
        return (List<TableColumn>) jdbcOperations.query(StrUtil.format(COLUMS_SQL_TMPL, tableName), mapper);
    }

    @Override
    public List<DBType> getTargetDB() {
        return ListUtil.toList(DBType.MYSQL,DBType.OB_MYSQL);
    }
}
